import React, { Component } from 'react';
import { connect } from 'dva';
import { Scrollbars } from 'react-custom-scrollbars';
import { Empty, Layout, message } from 'antd';
import { PageLoading } from '@ant-design/pro-layout';

import Dashboard from '@/components/Dashboard';
import GlobalFooter from '@/layouts/GlobalFooter';
import TreeMenuContent from '@/components/TreeMenuContent';
import FileFrame from '@/components/FileFrame';

import { HOST_IP } from '@/utils/constants';
import styles from '@/pages/subSystem/index.less';
import LeftMenus from '@/components/LeftMenus';
import Energy from '@/pages/energy/index';

const { Sider, Content } = Layout;

class index extends Component {

  constructor(props) {
    super(props);
    this.state = {
      selectedKey: ''
    }
  }


  handleClickTreeMenu = (selectedTreeMenu) => {
    this.setState({ selectedKey: selectedTreeMenu.key });
    this.props.dispatch({type:'subModule/selectTreeMenu', payload: {selectedTreeMenu}});
  }

  componentWillUnmount() {
    this.props.dispatch({type: 'subModule/clearAll'});
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.match.params.subModule !== this.props.match.params.subModule) {
      this.setState({ selectedKey: '' });
      const subModuleOrd = 'station:|h:' + nextProps.computedMatch.params.subModule;
      this.props.dispatch({type: 'subModule/fetch', payload: {subModuleOrd}});
    }
  }

  componentDidMount() {
    const { match, dispatch } = this.props;
    const subModuleOrd = 'station:|h:' + match.params.subModule;
    dispatch({type: 'subModule/fetch', payload: {subModuleOrd}});
  }

  render() {
    const { loading, moduleType, treeMenus, $typeSpec, navOrd, pagePath, url, dispatch } = this.props;
    if(loading) {
      return <PageLoading/>;
    }
    if(moduleType === 'DASHBOARD') {
      return (
        <Layout className={styles.subSystemPage} style={{background: 'transparent',overflow: 'hidden'}}>
          <Content className={styles.content} style={{background:'transparent',margin:0}}>
            <Scrollbars autoHide>
              <Dashboard dashboardRootOrd={`${navOrd}/dashboardRoot`}/>
            </Scrollbars>
          </Content>
          <GlobalFooter/>
        </Layout>
      );
    } else if(moduleType === 'HISTORY'|| moduleType === 'ALARM'||moduleType === 'TREE_MENU') {
      let { selectedKey } = this.state;
      if(!treeMenus || treeMenus.length === 0) {
        message.error('Tree Menu Root subnode is null!');
        return false;
      }
      let initTreeMenu = treeMenus[0];
      const defaultOpenKeys = [];
      while(initTreeMenu.children && initTreeMenu.children.length > 0) {
        defaultOpenKeys.push(initTreeMenu.key);
        initTreeMenu = initTreeMenu.children[0];
      }
      if(selectedKey === '') {
        selectedKey = initTreeMenu.key;
        dispatch({type:'subModule/selectTreeMenu', payload: {selectedTreeMenu: initTreeMenu}});
      }
      return (
        <Layout className={styles.subSystemPage}>
          <Sider theme='dark' style={{width: 300, maxWidth: 300, minWidth: 300}}>
            <Scrollbars autoHide>
              <LeftMenus menuList={treeMenus}
                         selectedKey={selectedKey}
                         menuClickCallback={this.handleClickTreeMenu}
              />
            </Scrollbars>
          </Sider>
          <Layout style={{overflow: 'hidden'}}>
            <Content className={styles.content}>
              <TreeMenuContent $typeSpec={$typeSpec}
                               moduleType={moduleType}
              />
            </Content>
            <GlobalFooter className={styles.footer}/>
          </Layout>
        </Layout>
      );
    } else if(moduleType === 'PAGE') {
      const inPagePath = pagePath.toLowerCase().trim();
      if(inPagePath.startsWith('/energy')) {
        return <Energy treeMenus={treeMenus} pagePath={inPagePath} />;
      }
      return <div>PAGE...: {pagePath}</div>;
    } else if(moduleType === 'IMAGE') {
      return (<img
        alt='example'
        style={{width:'100%',height:'100%'}}
        src={url}
      />);
    } else if(moduleType === 'TEXT') {
      return (
        <Empty
          className={'empty'}
          image='https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original'
          imageStyle={{
            height: 60,
          }}
          description={
            <span>{url}</span>
          }
        >
        </Empty>
      );
    } else if(moduleType === 'FILE') {
      return (
        <div style={{width:'100%', height:'100%', textAlign:'center', backgroundColor: '#ffffff', overflow: 'auto'}}>
          <FileFrame
            type={pagePath.toLowerCase().trim()}
            file={HOST_IP + '/ord/file:^' + url}
          />
        </div>
      );
    } else if(moduleType === 'URL') {
      if(url.startsWith('redirect:')) {
        window.location.href = url.replace('redirect:', '')
        return <PageLoading />;
      }
      const src = (url.startsWith("http://")||url.startsWith("https://"))?url: HOST_IP + '/ord/file:^' + url;
      return (
        <div style={{width:'100%', height:'100%', textAlign:'center', backgroundColor: '#ffffff', overflow: 'auto'}}>
          <iframe
            src={src}
            width="100%"
            height="100%"
            frameBorder="0"
            scrolling="no"
            allowFullScreen
          >
          </iframe>
        </div>
      );
    }
    return false;
  }
}

export default connect(({ subModule, loading }) => ({
  ...subModule,
  loading: loading.effects['subModule/fetch'],
}))(index);
